<template>
    <div class="page page-jobs">
        <v-table
            ref="vTable"
            v-model="list"
            :height="compact ? '350' : 'auto'"
            :columns="columns"
            :func="getList"
            :showPagination="false"
            :compact="compact"
            @selectionChange="handleSelectionChange"
            showCheckbox
            showIndex
        >
            <template #opts>
                <p-list-buttons
                    ref="btns"
                    :module="$options.name"
                    :buttons="buttons"
                    :compact="compact"
                    :ids="multipleSelection"
                    :list="list"
                    @clearIds="handleClearIds"
                    @editEnableChange="() => $emit('editEnableChange', true)"
                ></p-list-buttons>
            </template>
        </v-table>
    </div>
</template>

<script type="text/ecmascript-6">
import * as Chef from '../../../core/Chef.js';
import * as enums from '../../../store/status-enums.js';
import * as API from '../../../core/api.js';
import { mapState } from 'vuex';
import _ from 'lodash';
import bus from '../../../utils/Eventbus.js';
import vTable from '../../../utils/v-table/index.js';
import pListButtons from '../p-list-buttons.vue';
import Kernel from '../../../core/Kernel.js';

export default {
    name: 'jobs',
    components: { vTable, pListButtons },
    props: {
        compact: Boolean // 紧凑模式
    },
    data () {
        return {
            list: [],
            columns: [
                { label: 'icon icon-lock', prop: 'lockExt', width: 30, isIcon: true, align: 'center' },
                { label: this.$t('lang.id'), prop: 'id', width: 50, align: 'right' },
                { label: this.$t('lang.status'), prop: 'jobStatusExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.vehicleKey'), prop: 'vehicleKeyExt', width: 90 },
                { label: this.$t('lang.progress'), prop: 'progressExt', width: 80, isBranchground: true, align: 'right' },
                { label: this.$t('lang.deviation'), prop: 'deviationExt', width: 80 },
                { label: this.$t('lang.loop'), prop: 'jobLoopExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.label'), prop: 'label', width: 90 },
                { label: this.$t('lang.appointmentTime'), prop: 'appointmentTimeExt', sortProp: 'appointmentTime', width: 140 },
                { label: this.$t('lang.priority'), prop: 'priorityExt', sortProp: 'priority', width: 70, isBranchground: true, align: 'right' },
                { label: this.$t('lang.assignment'), prop: 'assignmentExt', width: 90 },
                // { label: this.$t('lang.initTime'), prop: 'initTimeExt', width: 130 },
                // { label: this.$t('lang.modified'), prop: 'modificationTimeExt', width: 130 },

                { label: this.$t('lang.initTime'), prop: 'initTimeExt', sortProp: 'initTime', width: 130 },
                { label: this.$t('lang.modified'), prop: 'modificationTimeExt', sortProp: 'modificationTime', width: 130 },
                { label: this.$t('lang.responsibility'), prop: 'responsibility', width: 110 },
                {
                    label: this.$t('lang.operate'),
                    fixed: 'right',
                    width: 180,
                    align: 'center',
                    opts: [
                        { label: this.$t('lang.detail'), type: 'info', icon: 'el-icon-document', callback: this.handleDetail },
                        { label: this.$t('lang.edit'), type: 'primary', icon: 'el-icon-edit', callback: this.handleModify },
                        { label: this.$t('lang.reset'), type: 'primary', icon: 'icon icon-rotateClockwise', callback: this.handleReset },
                        { label: this.$t('lang.lock'), type: 'warning', icon: 'el-icon-lock', callback: this.handleLock },
                        { label: this.$t('lang.delete'), type: 'danger', icon: 'el-icon-delete', callback: this.handleDelete }
                    ]
                }
            ],
            buttons: ['create', 'edit', 'reset', 'delete', 'lock', 'upload', 'download'],
            disableOpts: false,
            multipleSelection: []
        };
    },
    computed: {
        ...mapState({
            openedBoxes: state => state.businessStatus.openedBoxes,
            selectedJobs: state => state.businessStatus.selectedJobs,
            isAltFnActive: state => state.businessStatus.isAltFnActive
        })
    },
    watch: {
        compact: { handler () { this.init(); }, deep: true },
        // '$root.ws.serverTime'() { this.initAsync(); }
    },
    created() {
        bus.on(`${this.$options.name}.toggleRowSelection`, this.toggleRowSelection);
    },
    beforeDestroy() {
        this.$store.commit(enums.DESELECT_JOBS_ALL);
        bus.off(`${this.$options.name}.toggleRowSelection`, this.toggleRowSelection);
        if (this.kernel) this.kernel.off('handleIncrement', this.handleIncrementFunc);
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            // hide the opts columns in compact mode.
            let idx = this.columns.findIndex(v => v.opts);
            if (this.compact && idx >= 0) this.columns[idx].hidden = true;
            else if (idx >= 0) this.columns[idx].true = false;
            this.kernel = Kernel.getInstance();
            this.kernel.on('handleIncrement', this.handleIncrementFunc);
        },

        handleIncrementFunc(res) {
            if (!res || !res.refreshTypes || !res.refreshTypes[this.$options.name]) return;
            this.initAsync();
        },
        initAsync: _.throttle(function() {
            if (this.compact && this.openedBoxes.indexOf(`${this.$options.name}Table`) < 0) return;
            // TODO: if created or deleted, refresh the table components.
            if (!this.$root.resources.jobs || this.list.length !== this.$root.resources.jobs.length) {
                // hidden details
                /**
                 * 判断 this.$root.resources.jobs.length < this.list.length 说明是有任务完成的情况，
                 * 获取通过rootJobs和list比较算出完成了的任务IDS
                 * 判断是否精简版 && 是否有完成的任务IDS && 当前时候有选中的任务列表
                 * 然后删除掉任务列表选中的已完成任务IDS。--车辆多了有可能不准了
                 */
                // if (this.$root.resources && this.$root.resources.jobs && this.$root.resources.jobs.length < this.list.length) {
                //     let rootJobs = [];
                //     let list = [];
                //     this.$root.resources.jobs.map(v => {
                //         rootJobs.push(v.id);
                //     });
                //     this.list.map(v => {
                //         list.push(v.id);
                //     });
                //     console.error('任务有完成的了', rootJobs, list);
                //     let newRootJobs = new Set(rootJobs);
                //     let newList = new Set(list);
                //     let completeJobs = Array.from(new Set([...newList].filter(x => !newRootJobs.has(x))));
                //     console.error('完成的任务IDS',completeJobs);
                //     if (this.compact && completeJobs.length > 0 && this.selectedJobs[0]) {
                //         this.$store.commit(enums.DESELECT_JOBS, completeJobs);
                //         console.error('selectedJobs',this.selectedJobs);
                //     }
                // } else if (this.$root.resources && this.$root.resources.jobs && this.$root.resources.jobs.length > this.list.length) {
                //     console.error('新增任务了');
                // }
                // refresh v-table
                if (!this.$root.resources.jobs && this.list.length === 0) return;
                if (this.$refs.vTable && this.$refs.vTable.truename) bus.emit(`${this.$refs.vTable.truename}.init`);

                // hidden details
                let tag = this.selectedJobs && this.selectedJobs.length ? true : false;
                let idx = tag ? this.$root.resources.jobs.findIndex(v => v.id === this.selectedJobs[0]) : -1;
                if (idx < 0) {
                    // console.warn('CLOSE_FLOATER --------------> ', this.compact);
                    if (this.compact) this.$store.commit(enums.DESELECT_JOBS_ALL);
                    else this.$store.commit(enums.CLOSE_FLOATER);
                    // this.$emit('editEnableChange', false);
                }
                return;
            }
            this.list.forEach(v => {
                Chef.extendJobAsync(v, this.$root.resources.jobs);
            });
            // console.error(this.list);
        }, 1000),
        getList() {
            return API.getLocalResources(this.$options.name, this.$root).then(res => {
                let rtn = {...res};
                if (res && res.list && res.list.length) rtn.list = Chef.extendJobs(res.list);
                return rtn;
            });
        },
        // Trigger from table
        handleSelectionChange(ids) {
            console.log('jobs.handleSelectionChange: ', ids);
            this.$store.commit(enums.DESELECT_JOBS_ALL, ids);
            this.multipleSelection = ids;
            this.$emit('selectionChange', ids);
            if (!ids || !ids.length) return;
            let lastid = ids[ids.length - 1],
                vehicleId = Chef.getVehicleIdByJobId(lastid, this.$root.resources.jobs);
            bus.emit('p-painter-vehicles.locateVehicle', vehicleId);
        },
        // Trigger from vuex
        toggleRowSelection(ids) {
            console.log('jobs.toggleRowSelection: ', ids);
            this.$refs.vTable.toggleRowSelection(ids);
        },
        handleClearIds(ids) {
            console.log('jobs.handleClearIds: ', ids);
            this.multipleSelection = [];
            if (ids && ids.length) this.$store.commit(enums.DESELECT_JOBS_ALL, ids);
        },
        // opts callback
        handleDetail(e, row) {
            // this.$router.push({ name: 'job-detail', params: { type: 'read', ids: [row.id] } });
            this.$router.push({ name: 'job-detail', params: { type: 'read', id: row.id } });
        },
        handleModify(e, row) {
            // this.$router.push({ name: 'job-detail', params: { type: 'mod', ids: [row.id] } });
            this.$router.push({ name: 'job-detail', params: { type: 'mod', id: row.id } });
        },
        handleReset(e, row) {
            this.$refs.btns.handleReset(e, [row.id]);
        },
        handleLock(e, row) {
            this.$refs.btns.handleLock(e, [row.id]);
        },
        handleDelete(e, row) {
            this.$refs.btns.handleDelete(e, [row.id]);
        }
    }
};
</script>

<style lang="scss">
.page-Jobs {
}
</style>
